package com.test.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.test.entity.User;
import com.test.entity.Users;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.rmi.server.UID;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class TokenUtil {


    public static String getTokenUserId() {
        String token = getRequest().getHeader("token");// 从 http 请求头中取出 token
        String userId = JWT.decode(token).getAudience().get(0);
        return userId;
    }

    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }

    public String getToken(Users user) {
        String token = "";
        token = JWT.create().withAudience(user.getU_acount())
                .sign(Algorithm.HMAC256(user.getU_password()));
        return token;
    }


    public static Users getUsersInfo(String token) {
        if (token != null && !"".equals(token)) {
            Jedis jedis = new Jedis("localhost");
            Map<String, Object> listbreed = (Map<String, Object>) JSONArray.parse(jedis.get(token));
            Users user = new Users();
            user.setU_acount(listbreed.get("u_acount").toString());
            user.setU_Identity(listbreed.get("u_Identity").toString());
            user.setU_name(listbreed.get("u_name").toString());
            user.setU_password(listbreed.get("u_password").toString());
            user.setU_status(listbreed.get("u_status").toString());
            user.setU_id(Integer.parseInt(listbreed.get("u_id").toString()));
            return user;
        } else {
            return null;
        }
    }

    public static Boolean removeRedisUserInfo(String token) {
        if (token != null && !"".equals(token)) {
            Jedis jedis = new Jedis("localhost");
            if (jedis.del(token) == 1) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }
    }

}
